package cn.objectspace.webssh.controller;

import cn.objectspace.webssh.config.SpringContextUtil;
import cn.objectspace.webssh.service.IRealTimeLogsService;
import com.jcraft.jsch.Channel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author xuejingbao
 * @create 2022-11-18 9:12
 */
@Slf4j
@Getter
@Setter
@Component
@ServerEndpoint(value = "/log")
public class RealTimeLogsWebSocket {

    private final static IRealTimeLogsService realTimeLogsService = SpringContextUtil.getBean(IRealTimeLogsService.class);


    private Session session;

    private Channel channel;

    /**
     * 连接成功后调用的方法
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        // 创建对应连接，并执行对应指令
        this.session = session;
        realTimeLogsService.initConnection(this);
    }

    @OnMessage
    public void onMessage(String message) {
        realTimeLogsService.execute(this, message);
    }

    @OnClose
    public void onClose() {
        releaseResource();
    }

    @OnError
    public void onError(Throwable error) {
        releaseResource();
        log.error("ws报错", error);
    }

    /**
     * 释放资源
     */
    public void releaseResource() {
        realTimeLogsService.closeConnection(this);
        try {
            if (!ObjectUtils.isEmpty(this.session)) {
                this.session.close();
            }
        } catch (IOException e) {
            log.warn("ws释放资源", e);
        }
    }

}
